<?php
/*
 module:		会员充值订单
 create_time:	2022-04-05 20:59:05
 author:	陕西格创
 contact:		
*/

namespace app\api\controller;

use app\api\model\MoneyBalanceLog;
use app\api\model\ZhMatchmakerCash;
use app\api\service\ZhMatchmakerOrderService;
use app\api\service\ZhVipOrderService;
use app\api\model\ZhMatchmakerOrder as ZhMatchmakerOrderModel;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;
use app\api\model\SysSite as SysSiteModel;
use app\api\model\Member as MemberModel;
use app\api\model\ZhMPayLog as ZhmPayLogModel;
use app\api\service\PaymentService;

class ZhMatchmakerOrder extends Common
{

    function test(){
        $res=file_put_contents('a.txt','  vvvvvvv' . date('Y_m_d'),FILE_APPEND);
        print_r($res);
    }

    function index()
    {



        $wxapp_id = $this->request->get('wxapp_id');
        $a_id      = $this->request->get('a_id');
        $m_id      = $this->request->get('m_id');
        $status  = $this->request->get('status');
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }
        $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
        if (!$wxSetting) {
            return $this->ajaxReturn($this->errorCode, '平台参数未配置');
        }

       /* $authentication = \app\api\model\ZhAuthentication::where(['id' => $a_id, 'wxapp_id' => $wxapp_id])->find();
        if (!$authentication) {
            return $this->ajaxReturn($this->errorCode, '未知用户');
        }*/
        $limit = $this->request->get('limit', 20, 'intval');
        $page  = $this->request->get('page', 1, 'intval');
        $where             = [];
        $where['o.wxapp_id'] = $wxapp_id;
        if($status){
            $where['o.status']   = $status;
        }
        if($a_id){
            $where['o.a_id']     = $a_id;
        }
        if($m_id){
            $where['o.m_id']     = $m_id;
        }
        $res = ZhMatchmakerOrderService::indexList(formatWhere($where), $limit, $page);
        foreach ($res['rows'] as &$v) {
            $v['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
            if($v['updatetime']){
                $v['updatetime'] = date('Y-m-d H:i:s', $v['updatetime']);
            }
        }
        return $this->ajaxReturn($this->successCode, '返回成功', htmlOutList($res));
    }


    function view()
    {
        $id= $this->request->get('id');
        if(!$id) $this->error('参数错误');
        $sql = 'select  o.id,o.m_id,o.a_id,o.price,o.status,o.order_sn,o.price,o.createtime,
                gc_zh_authentication.real_name a_name,gc_zh_matchmaker.name  m_name,
                c.entry_name,c.comment,c.is_fixed_price
                from gc_zh_matchmaker_order  as o  
                left join gc_zh_matchmaker  on o.m_id=gc_zh_matchmaker.matchmaker_id
                 left join  gc_zh_authentication on o.a_id=gc_zh_authentication.authentication_id
                left join gc_zh_matchmaker_charge  c on  o.c_id=c.id
                where o.id = '.$id.' limit 1';
        $info = Db::connect('mysql')->query($sql)[0];

        $info["createtime"]=date("Y-m-d H:i:s",$info["createtime"]);

        return $this->ajaxReturn($this->successCode, '返回成功', $info);
    }
    //红娘发起收费
    function add()
    {
        $wxapp_id = $this->request->post('wxapp_id');
        $m_id     = $this->request->post('m_id');
        $c_id     = $this->request->post('c_id');
        $price= $this->request->post('price');

        $type     = $this->request->post('type', 'wx', 'serach_in');
        $c_type=0; $uid=0;
        if (!$wxapp_id) {
            return $this->ajaxReturn($this->errorCode, '缺少平台参数');
        }else{
            $wxSetting = SysSiteModel::where('wxapp_id', $wxapp_id)->find();
            if (!$wxSetting) {
                return $this->ajaxReturn($this->errorCode, '平台参数未配置');
            }
        }
        if (!$m_id) {
            return $this->ajaxReturn($this->errorCode, '缺少红娘id参数');
        }else{
            $matchmaker=\app\api\model\ZhMatchmaker::find($m_id);
            $level=$matchmaker["level_id"];
            if (!$matchmaker) {
                return $this->ajaxReturn($this->errorCode, '未知红娘用户');
            }

        }

        if (!$c_id) {
            return $this->ajaxReturn($this->errorCode, '缺少收费项目id参数');
        }else{
            $charge=\app\backend\model\ZhMatchmakerCharge::find($c_id);
            if (!$charge) {
                return $this->ajaxReturn($this->errorCode, '未知收费项目');
            }
            $c_type=$charge["is_fixed_price"];//0固定 1自定义
            //项目固定金额，根据红娘级别去获取价格
            if($c_type==0){
                if($level==0){
                    return $this->ajaxReturn($this->errorCode, "红娘用户未完善级别，  红娘id {$m_id} level_id {$level} ");
                }
                $matchmaker_money_json=json_decode(html_entity_decode($charge["matchmaker_money_json"]),1);
                foreach ($matchmaker_money_json as $k=>$v){
                    if($v["level_id"]==$level){
                        $price=$v["toll_money"];
                    }
                }
                if($price==0||$price==""){
                    return $this->ajaxReturn($this->errorCode, "请配置收费项目{$c_id}红娘级别{$level}的金额");
                }
            }else{
                if($price==0||$price==""){
                    return $this->ajaxReturn($this->errorCode, '请红娘设置自定义收费项目的金额');
                }
            }
        }

        $zhmatchmakerOrderId = ZhMatchmakerOrderModel::insertGetId([
            'wxapp_id'         => $wxapp_id,
            'order_sn'         => $m_id . '0' . $wxapp_id . time() . rand(100, 999),
            'status'           => 0,
            'm_id'             => $m_id,
            'a_id'             => 0,
            'c_id'             => $c_id,
            'price'            => $price,
            'c_type'           => $c_type,
            'createtime'       => time()
        ]);
        if ($zhmatchmakerOrderId) {
            return $this->ajaxReturn($this->successCode, '操作成功', ['order_id' => $zhmatchmakerOrderId]);
        }else{
            return $this->ajaxReturn($this->errorCode, '操作失败');
        }

    }

    //佳人绑定订单  生成订单
    function update()
    {
        $wxapp_id = $this->request->post('wxapp_id');
        $a_id       = $this->request->post('a_id' );
        $id       = $this->request->post('id' );
        $order=\app\api\model\ZhMatchmakerOrder::find($id);
        $uid=0;
        if (!$order) {
            return $this->ajaxReturn($this->errorCode, '订单不存在');
        }
      /*  if (!$a_id) {
            return $this->ajaxReturn($this->errorCode, '缺少佳人id参数');
        }else{
            $authentication=\app\api\model\ZhAuthentication::find($a_id);
            if (!$authentication) {
                return $this->ajaxReturn($this->errorCode, '未知佳人用户');
            }
            $uid=$authentication["u_id"];
        }*/
        if(intval($uid)==0){
            return $this->ajaxReturn($this->errorCode, '未知佳人用户');
        }else{
            $user = MemberModel::where(['uid' => $uid, 'wxapp_id' => $wxapp_id])->find();
            if (!$user) {
                return $this->ajaxReturn($this->errorCode, '佳人用户数据不存在');
            }
        }

        $sql = 'select  o.id,o.m_id,o.a_id,o.price,o.status,o.order_sn,o.price,o.createtime,
                gc_zh_authentication.real_name a_name,gc_zh_matchmaker.name  m_name,
                c.entry_name,c.comment,c.is_fixed_price
                from gc_zh_matchmaker_order  as o  
                left join gc_zh_matchmaker  on o.m_id=gc_zh_matchmaker.matchmaker_id
                 left join  gc_zh_authentication on o.a_id=gc_zh_authentication.authentication_id
                left join gc_zh_matchmaker_charge  c on  o.c_id=c.id
                where o.id = '.$id.' limit 1';
        $info = Db::connect('mysql')->query($sql)[0];
        $info["createtime"]=date("Y-m-d H:i:s",$info["createtime"]);

        //已经绑定佳人，返回订单
        if(intval($order["a_id"])>0){

            return $this->ajaxReturn($this->successCode, '佳人已绑定订单',['order' => $info]);
        }else{
            $res=\app\api\model\ZhMatchmakerOrder::where([
                'id' =>$id
            ])->update(['a_id' =>$a_id]);

            $sql = 'select  o.id,o.m_id,o.a_id,o.price,o.status,o.order_sn,o.price,o.createtime,
                gc_zh_authentication.real_name a_name,gc_zh_matchmaker.name  m_name,
                c.entry_name,c.comment,c.is_fixed_price
                from gc_zh_matchmaker_order  as o  
                left join gc_zh_matchmaker  on o.m_id=gc_zh_matchmaker.matchmaker_id
                 left join  gc_zh_authentication on o.a_id=gc_zh_authentication.authentication_id
                left join gc_zh_matchmaker_charge  c on  o.c_id=c.id
                where o.id = '.$id.' limit 1';
            $info = Db::connect('mysql')->query($sql)[0];
            $info["createtime"]=date("Y-m-d H:i:s",$info["createtime"]);
            if($res){
                return $this->ajaxReturn($this->successCode, '佳人绑定订单成功',['order' => $info]);
            }else{
                return $this->ajaxReturn($this->errorCode, '填充佳人失败',['order' => $info]);
            }
        }

    }

    /**
     * 发起支付
     * 目前的逻辑，发起支付邀请的页面，只能对一个用户发起支付，用户收到后，将这笔支付的openid 变更为自己的
     *
     * @author lichunguang
     * @since 2024/5/26 21:55
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function pay()
    {
        $id       = $this->request->post('id' );
        $type     = $this->request->post('type', 'wx', 'serach_in');
        $openId   = $this->request->post('openid' );
        if(!$openId){
            return $this->ajaxReturn($this->errorCode, 'openid不能为空');
        }
        //填写openid
          ZhMatchmakerOrderModel::where([
              'id' =>$id
          ])->update(['open_id' => $openId,'updatetime'=>time()]);
        file_put_contents('a.txt','填写订单openid_id' . $openId. date('Y_m_d H:i:s'),FILE_APPEND);
        $OrderData=ZhMatchmakerOrderModel::find($id);
        if (!$OrderData) {
            return $this->ajaxReturn($this->errorCode, '订单不存在');
        }
        $wxapp_id=$OrderData["wxapp_id"];
        $pay_price=$OrderData["price"];
        //生成支付记录
        $res = ZhmPayLogModel::insert([
            'wxapp_id'         =>$wxapp_id ,
            'a_uid'              => 0,
            'order_sn'         => $OrderData['order_sn'],
            'price'            => $OrderData['price'],
            'o_id'              =>$id,
            'status'           => 0,
            'type'             => '红娘收费',
            'a_id'           => 0,
            'c_id'         => $OrderData['c_id'],
            'openid'        =>$openId,
            'm_id'        => $OrderData['m_id'],
            'create_time'      => time()
        ]);

        file_put_contents('a.txt','插入数据ZhmPayLog' .   date('Y_m_d H:i:s'),FILE_APPEND);

        if($res){
            try {
                //支付回调的地址
                $notify_url = 'http://' . $_SERVER['HTTP_HOST'] . '/api/ZhMatchmakerOrder/payResult/wxapp_id/' . $wxapp_id;
                if ($type == 'wx') {
                    $trade_type = 'JSAPI';
                } elseif ($type == 'app') {
                    $trade_type = 'APP';
                } elseif ($type == 'H5') {
                    $trade_type = 'MWEB';
                } elseif ($type == 'H5-wx') {
                    $trade_type     = 'JSAPI';
//                    $user['openid'] = $user['official_account_openid'];
                }
                //生成支付链接
                $js_pay = PaymentService::instance($wxapp_id, $type)->create($openId, $OrderData['order_sn'], $pay_price, '红娘付费', ['notify_url' => $notify_url], $trade_type);
                return $this->ajaxReturn($this->successCode, '操作成功', ['order' => $OrderData['order_sn'], 'paydata' => $js_pay]);
            } catch (\Exception $e) {
                return $this->ajaxReturn($this->errorCode, $e->getMessage());
            }
        }else{
            file_put_contents('a.txt','写入paylog失败' .   date('Y_m_d H:i:s'),FILE_APPEND);
            return $this->ajaxReturn($this->errorCode, '写入paylog失败');
        }

    }

    // 支付回调
    public function payResult()
    {
        $wxapp_id = input('wxapp_id');
        file_put_contents('log.txt','进入回调' . date('Y_m_d'));
        $app      = PaymentService::instance($wxapp_id)::getPayApp();
        $response = $app->handlePaidNotify(function ($message, $fail) use ($wxapp_id) {
            trace($message, 'notify_' . date('Y_m_d'));
            $order = ZhMatchmakerOrderModel::where(['order_sn' => $message['out_trade_no']])->find();
            if (!$order || $order->status == 1) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                file_put_contents('a.txt','支付成功 SUCCESS' .   date('Y_m_d H:i:s'),FILE_APPEND);

                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    //1、修改订单支付状态
                    ZhMatchmakerOrderModel::where([
                        'order_sn' => $message['out_trade_no'],
                        'wxapp_id' => $wxapp_id
                    ])->update(['status' => 1,'updatetime'=>time()]);
                    file_put_contents('a.txt','修改订单status' .   date('Y_m_d H:i:s'),FILE_APPEND);

                    ZhmPayLogModel::where([
                        'order_sn' => $message['out_trade_no'],
                        'wxapp_id' => $wxapp_id
                    ])->update(['status' => 1, 'wx_order_sn' => $message['transaction_id']]);
                    file_put_contents('a.txt','修改mpaylog' .   date('Y_m_d H:i:s'),FILE_APPEND);

                    //2、给红娘分成
                    $this->sendMatchmakerPrize($order);
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            return true; // 返回处理完成
        });
        return $response->send(); // return $response;
    }


    /**
     * 发放红娘分成
     * @author lichunguang
     * @since 2024/6/2 15:50
     * @param $order
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function sendMatchmakerPrize($order){
        if(empty($order)){
            return;
        }
        $order = $order->toArray();
        //$order = ZhMatchmakerOrderModel::find(206)->toArray();
        $wxapp_id = $order['wxapp_id'];

        //print_r($order);exit;
        //2、给红娘分成
        $c_id=$order["c_id"];
        $m_id=$order["m_id"];
        $charge=\app\backend\model\ZhMatchmakerCharge::find($c_id);
        //print_r($charge->toArray());exit;
        if($charge){
            $is_fixed_price=intval($charge["is_fixed_price"]);
            //print_r($is_fixed_price);exit;
            $matchmaker=\app\api\model\ZhMatchmaker::where("matchmaker_id",$m_id)->find();
            //print_r($matchmaker);exit;
            if($matchmaker){
                $matchmaker_price=0;
                $level=$matchmaker["level_id"];
                $matchmaker_money_json=json_decode(html_entity_decode($charge["matchmaker_money_json"]),1);
                //print_r($matchmaker_money_json);exit;
                foreach ($matchmaker_money_json as $k=>$v){
                    if($v["level_id"]==$level){
                        if($is_fixed_price==0){//固定金额
                            $matchmaker_price=$v["commission_rate"];
                        }else{
                            //print_r($order["price"]);
                            //echo "aaa";exit;
                            $matchmaker_price=($v["commission_rate"]/100)*$order["price"];
                        }
                    }
                }
                //print_r($matchmaker_price);exit;
                //添加红娘分成表数据
                if($matchmaker_price>0){
                    $cashData = [
                        'wxapp_id'         => $wxapp_id,
                        'm_uid'              => $matchmaker["u_id"],
                        'o_id'         => $order['id'],
                        'price'            => $matchmaker_price,
                        'status'           => 0,
                        'a_id'           => $order['a_id'],
                        'c_id'         => $order['c_id'],
                        'm_id'        => $order['m_id'],
                        'description'=>$order["entry_name"],
                        'createtime'      =>time()
                    ];
                    $res = ZhMatchmakerCash::insert($cashData);
                    if(!$res){
                        file_put_contents('a.txt','创建zhmatchmakercash失败' .   date('Y_m_d H:i:s'),FILE_APPEND);
                    }
                    //修改红娘余额
                    $member=MemberModel::where("uid",$matchmaker["u_id"])->find();
                    $virtual_currency_balance=doubleval($member["balance"])+$matchmaker_price;
                    $res=\app\api\model\Member::where(['uid' =>$matchmaker["u_id"]])->update(['balance' =>$virtual_currency_balance]);

                    $data = [
                        'u_id'          => $matchmaker["u_id"],
                        'wxapp_id'      => $wxapp_id,
                        'start_balance' => $member['balance'],
                        'end_balance'   => $virtual_currency_balance,
                        'type'          => '收入',
                        'remake'        => $charge['entry_name'].' 红娘分成',
                        'create_time'   => time(),
                        'num'           => $virtual_currency_balance,
                        'order_no' => $order['order_sn']
                    ];
                    MoneyBalanceLog::insert($data);
                    if($res){
                        file_put_contents('a.txt','修改用户余额' .$virtual_currency_balance.   date('Y_m_d H:i:s'),FILE_APPEND);
                        trace("修改用户余额 ".$virtual_currency_balance, 'notify_' . date('Y_m_d'));
                    }else{
                        file_put_contents('a.txt','修改用户余额失败' .   date('Y_m_d H:i:s'),FILE_APPEND);
                        trace("修改用户余额失败", 'notify_' . date('Y_m_d'));
                    }
                }else{
                    file_put_contents('a.txt',' matchmaker_price==0 无法分成' .   date('Y_m_d H:i:s'),FILE_APPEND);

                }
            }else{
                file_put_contents('a.txt',' matchmaker为空' .   date('Y_m_d H:i:s'),FILE_APPEND);

            }

        }else{
            trace('charge 不存在 ' , ' time ' . date('Y_m_d'));
            file_put_contents('a.txt','charge 不存在' .   date('Y_m_d H:i:s'),FILE_APPEND);

        }
    }

}

